package com.jf.concurrent.lock.cas;

import java.util.concurrent.atomic.AtomicReference;

import static java.lang.System.out;

/**
 * 自己实现的 自旋锁
 *
 * @author Junfeng
 */
public class SplnLockDemo {

    /**
     * 线程原子引用
     */
    AtomicReference<Thread> atomic = new AtomicReference<>();

    /**
     * 加锁
     */
    public void lock() {
        while (!atomic.compareAndSet(null, Thread.currentThread())) {
        }
        out.println(Thread.currentThread().getName() + " 获得了锁");
    }

    /**
     * 解锁
     */
    public void unlock() {
        atomic.compareAndSet(Thread.currentThread(), null);
        out.println(Thread.currentThread().getName() + " 解了锁");
    }

    public static void main(String[] arg) {
        SplnLockDemo splnLockDemo = new SplnLockDemo();

        new Thread(() -> {
            splnLockDemo.lock();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                splnLockDemo.unlock();
            }
        }, "A").start();

        new Thread(() -> {
            splnLockDemo.lock();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                splnLockDemo.unlock();
            }
        }, "B").start();
    }
}
